<?php
/**
 * SQL_Prepare, 实现 bindParam()
 *
 * @filesource _sql_prepare.php
 * @package peck
 * @subpackage _db
 * @version $id: 0.1, utf8, Tue Jan 12 21:23:49 CST 2010
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2010 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example 
 *   
 */
abstract class SQL_Prepare{
	/**
	 *  预执行的语句
	 * 
	 * @var $prepare string
	 */
	protected $prepare = null;
	
	/**
	 * 等待替换的
	 * 
	 * @var $params array
	 */
	protected $params = array();
	
	//临时数据库连接
	protected $db;
    
    //零时statement
    protected $stmt;

	public function __construct($db, $stmt=null, $prepare=null){
		$this->prepare = $prepare;
        $this->db = $db;
        $this->stmt = $stmt;
	}
	
	public function __destruct(){
		unset($this->prepare);
        unset($this->params);
	}
	
	/**
	 * 绑定 params
	 * 
	 * @param mixed $key
	 * @param mixed $param
	 */
	public function bindParam($key, &$param){
		$this->params[$key] = $param;
	}
	
    public function execute(){
        $prepare = $this->prepare;

		if( array_key_exists(1, $this->params) ){
			//使用 '?' 编码
			$arr = explode('?', $prepare);
			foreach($this->params as $k=>$v){
				$i = $k-1;
				$arr[$i] = $arr[$i].' '.$this->escape((string)$v);
			}
			$prepare = implode(' ', $arr); 
		}else{
            //使用 ':key' 编码
            $sum = count($this->params);
            if($sum > 0){
                $i = 1;
                foreach($this->params as $k=>$v){
                    if($i == 1){
                        $pattern = '/('.preg_quote($k).')';
                        $i++;
                    }else{
                        $pattern .= '|('.perg_quote($k).')';
                    }
                }
                $pattern .= '/';
                $arr = preg_split($pattern, $prepare, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
                foreach($arr as $k=>$v){
                    if( array_key_exists($v, $this->params) ){
                        $arr[$k] = $this->escape((string)$this->params[$v]);
                    }
                }
			    $prepare = implode(' ', $arr); 
            }//END sum>0
		}//END key type

        return $this->query($prepare);
	}//END func execute

    /**
     * 保持SQL语句变量的合法性
     */
    abstract protected function escape($value);

    /**
     * 查询SQL语句
     */
    abstract protected function query($sql);    
	
}//END class SQL_Prepare
?>
